<template>
  <!-- 定义一个容器用于显示网络拓扑图 -->

  <div id="network-topology" style="width: 100%; height: 100%;"></div>

</template>

<script>
import { loadConfig } from '@/utils/config';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'NetworkTopology',
  components: {
  },
  data() {
    return {
      myChart: null,
      selectedNodeName: '', // 存储点击的节点名称
      currentComponent: null,
      loadData: { //保存结点的负载值
        upf0: 10,
        upf1: 10,
        upf2: 10,
        upf3: 10
      },
      interval: null,
      option: {
        initChart: {
          graphic: [
						{
							type: 'rect',
							shape: {
								x: 30, // 左上角 x 坐标
								y: 220, // 左上角 y 坐标
								width: 760, // 宽度
								height: 440, // 高度
							},
							style: {
								stroke: '#FFFFFF', // 边框颜色
								lineWidth: 5, // 边框宽度
								fill: 'none', // 无填充
								lineDash: [4, 6], // 虚线样式
							},
						},
					],
          series: [
            {
              type: 'graph',
              layout: 'none',
              data: [
                { name: 'SMF', x: 130, y: 50, symbol: 'image://' + require('@/assets/icon/server.png'), symbolSize: [80, 90] },
                { name: 'NWDAF', x: 178, y: 50, symbol: 'image://' + require('@/assets/icon/nwdaf1.png'), symbolSize: [100, 90] },
                { name: 'UPF-0', x: 100, y: 100, symbol: 'image://' + require('@/assets/icon/nwdaf2.png'), symbolSize: [100, 90], label: { position: 'left', formatter: '{b}\n10% ' } },
                { name: 'UPF-1', x: 100, y: 160, symbol: 'image://' + require('@/assets/icon/nwdaf2.png'), symbolSize: [100, 90], label: { position: 'left', formatter: '{b}\n10% ' } },
                { name: 'UPF-2', x: 200, y: 100, symbol: 'image://' + require('@/assets/icon/nwdaf2.png'), symbolSize: [100, 90], label: { formatter: '{b}\n 10%' } },
                { name: 'UPF-3', x: 200, y: 160, symbol: 'image://' + require('@/assets/icon/nwdaf2.png'), symbolSize: [100, 90], label: { formatter: '{b}\n 10%' } },
                { name: '网元结点', x: 100, y: 200, symbol: 'image://' + require('@/assets/icon/server.png'), symbolSize: [60, 60], label: { fontSize: 24 } },
                { name: 'Agent', x: 147, y: 200, symbol: 'image://' + require('@/assets/icon/leaf.png'), symbolSize: [60, 60], label: { fontSize: 24 } },
                { name: '联邦中心', x: 185, y: 200, symbol: 'image://' + require('@/assets/icon/leaf2.png'), symbolSize: [60, 60], label: { fontSize: 24 } },
                { name: 'UPF中心点', x: 130, y: 80, symbol: 'none', symbolSize: [40, 40], label: { show: false } },
                { name: '联邦连接点', x: 170, y: 60, symbol: 'none', symbolSize: [40, 40], label: { show: false } },
                { name: 'NWDAF中心点', x: 170, y: 80, symbol: 'none', symbolSize: [40, 40], label: { show: false } },
              ],
              links: [
                { source: 'UPF-0', target: 'UPF-2', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' } },
                { source: 'UPF-0', target: 'UPF-3', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' } },
                { source: 'UPF-1', target: 'UPF-2', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' } },
                { source: 'UPF-1', target: 'UPF-3', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' } },
                { source: 'SMF', target: 'UPF中心点', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' } },
                { source: '联邦连接点', target: 'NWDAF中心点', label: { show: true, formatter: '', position: 'middle', rotate: 0, color: 'white' }, lineStyle: { color: '#e44b18' }  },                
              ], // 初始化为空
              label: {
                show: true,
                position: 'right',
                formatter: '{b}',
                color: 'white',
                fontSize: 30,
              },
              lineStyle: {
                curveness: 0,
                width: 5,
                color: 'white',
                opacity: 1,
              },
              
              // markLine: {
              //   data: [
              //     [
              //       { coord: [70, 120] },  // 水平线起点
              //       { coord: [230, 120] } // 水平线终点
              //     ],
              //   ],
              //   name: 'bus',
              //   lineStyle: {
              //     type: 'solid',
              //     color: 'white',
              //     width: 2
              //   },
              //   symbol: 'none',
              //   tooltip: {
              //     show: true,
              //     formatter: 'bus line'
              //   }
              // }
            }
          ],
        },
      }
    };
  },
  mounted() {
    this.initChart();
    this.fetchData();
    this.interval = setInterval(this.fetchData, 2000);
  },
  beforeUnmount() {
    if (this.myChart) {
      this.myChart.dispose();
    }
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  methods: {
    initChart() {
      const container = document.getElementById('network-topology');
      if (container) {
        this.myChart = echarts.init(container);
        this.$nextTick(() => {
          this.myChart.setOption(this.option.initChart);
          this.myChart.on('click', this.handleNodeClick);
        })
      }
    },
    handleNodeClick(params) {
      this.selectedNodeName = params.name.toLowerCase(); // 更新点击的节点名称
      const componentMap = {
        'UPF-0': "GraphNode",
        'UPF-1': "GraphNode",
        'UPF-2': "GraphNode",
        'UPF-3': "GraphNode",
        "NWDAF": "GraphNode",
      };
      const componentName = componentMap[params.name];
      if (componentName) {
        this.$emit("node-click", params.name); // 向父组件传递点击的节点名称
      }
    },
    showOriginalTopology() {
      this.showDetail = false; // 隐藏详情，展示原始拓扑图
      this.currentComponent = null;
      this.selectedNodeName = ''; // 重置点击的节点名称
      this.clearIntervalInComponent(); // 清除子组件中的定时器
      if (this.myChart) {
        this.myChart.dispose();
      }
      // 重新初始化图表
      this.$nextTick(() => {
        this.initChart();
      });

      // 如果子组件存在且有销毁图像的方法，调用销毁方法
      const detailComponent = this.$refs.detailComponent;
      if (detailComponent && detailComponent.destroyChart) {
        detailComponent.destroyChart(); // 调用子组件的销毁方法
      }
    },
    clearIntervalInComponent() {
      if (this.$refs.detailComponent && this.$refs.detailComponent.intervalId) {
        clearInterval(this.$refs.detailComponent.intervalId);
      }
    },
    async fetchData() {
      const config = await loadConfig();
      const apiUrl = config.apiUrl;
      axios.get(`${apiUrl}/getDB?table=prediction_data`).then(res => {
        // console.log(res);
        if (res.data && res.data.length > 0) {
          this.loadData = {
            upf0: res.data[res.data.length-1].upf0_load || 0.1,
            upf1: res.data[res.data.length-1].upf1_load || 0.1,
            upf2: res.data[res.data.length-1].upf2_load || 0.1,
            upf3: res.data[res.data.length-1].upf3_load || 0.1,
          }
        }
        this.updateChartLabels();
      }).catch(error => {
        console.error("Error fetching data: ", error);
      })
    },
    // 更新图标的名称（增加负载值）
    updateChartLabels() {
      const option = this.myChart.getOption();
      const series = option.series[0];
      
      // 更新UPF节点的标签
      series.data = series.data.map(node => {
        let loadValue;
        switch(node.name) {
          case 'UPF-0':
            loadValue = this.loadData.upf0;
            break;
          case 'UPF-1':
            loadValue = this.loadData.upf1;
            break;
          case 'UPF-2':
            loadValue = this.loadData.upf2;
            break;
          case 'UPF-3':
            loadValue = this.loadData.upf3;
            break;
          default:
            return node;
        }
        loadValue = (loadValue * 100).toFixed(1); // 保留两位小数
        let color;
        if (loadValue < 40) {
          color = '#91cc75';
        } else if (loadValue < 80) {
          color = '#fac858';
        } else {
          color = '#e44b18';
        }
      
        return {
          ...node,
          label: {
            ...node.label,
            formatter: `{b}\n${loadValue}%`,
            color: color
          }
        };
      });
      
      this.myChart.setOption({
        series: [series]
      });
    }
  }
};
</script>

<style scoped>
/* 设置容器的宽度和高度 */
#network-topology {
  position: relative;
  width: 100%;
  height: 100%;
}

.return-icon {
  position: absolute;
  left: 10px;
  top: -30px;
  background-color: transparent;
  color: cyan;
  font-size: 40px;
  cursor: pointer;
  outline: none;
  z-index: 1;
}

.return-icon::after {
  content: '首页';
  /* 这是要显示的文字 */
  position: absolute;
  left: 100%;
  /* 将文字放置在图标的右侧 */
  top: 50%;
  transform: translateY(-50%);
  /* 垂直居中对齐 */
  white-space: nowrap;
  /* 防止文字换行 */
  background-color: transparent;
  /* 背景颜色 */
  color: cyan;
  /* 文字颜色 */
  padding: 2px 4px;
  /* 内边距 */
  border-radius: 4px;
  /* 圆角 */
  opacity: 0;
  /* 默认隐藏 */
  transition: opacity 0.3s;
  /* 过渡效果 */
  pointer-events: none;
  /* 防止伪元素影响点击事件 */
  font-size: 24px;
  font-weight: bold;
}

.return-icon:hover::after {
  opacity: 1;
  /* 鼠标悬停时显示 */
  pointer-events: auto;
  /* 鼠标悬停时允许点击 */
}
</style>
